const task_report = async (data) => {
  const response = await fetch(
    "https://qianniu.bingdou.site/v1/xhs/task/report",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    }
  );
  return response.json();
};
const account_maintenance_task_report = async (data) => {
  const response = await fetch(
    "https://qianniu.bingdou.site/v1/xhs/account_maintenance_task/list",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    }
  );
  return response.json();
};

const openBrowser = async (
  ads_power,
  headless,
  task,
  key,
  filename,
  user,
  pythons
) => {
  if (!(user && user.userInfo && user.userInfo.token)) return;

  const { ads_power_id, xhs_user_id } = ads_power;
  self.postMessage({
    type: "fetch",
    url: `http://local.adspower.net:50325/api/v1/browser/start?user_id=${encodeURIComponent(
      ads_power_id
    )}&ip_tab=0&open_tabs=1&headless=${headless}`,
    options: {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    },
  });

  // 等待主线程返回 fetch 的响应数据
  const start_result = await new Promise((resolve) => {
    self.addEventListener("message", (event) => {
      if (event.data.type === "fetchResponse") {
        resolve(event.data.response);
      }
    });
  });

  if (!start_result.data) return;
  const { ws, webdriver } = start_result.data;

  const {
    images,
    comment,
    text,
    title,
    videos,
    collect_limit,
    collect_rate,
    comment_limit,
    comment_rate,
    comments,
    keywords,
    like_limit,
    like_rate,
  } = task.config;

  const { duration, id } = task;

  let args;
  switch (key) {
    case "c":
      args = [
        `'${ws.selenium}'`,
        `'${webdriver}'`,
        `'${images.join(",")}'`,
        `'${title}'`,
        `'${text}'`,
        `'${comment}'`,
      ];
      break;
    case "c_win":
      args = [
        `"${ws.selenium}"`,
        `"${webdriver}"`,
        `"${images.join(",")}"`,
        `"${title}"`,
        `"${text}"`,
        `"${comment}"`,
      ];
      break;
    case "d":
      args = [
        `'${ws.selenium}'`,
        `'${webdriver}'`,
        `'${videos.join(",")}'`,
        `'${title}'`,
        `'${text}'`,
        `'${comment}'`,
      ];
      break;
    case "d_win":
      args = [
        `"${ws.selenium}"`,
        `"${webdriver}"`,
        `"${videos.join(",")}"`,
        `"${title}"`,
        `"${text}"`,
        `"${comment}"`,
      ];
      break;
    case "e":
      args = [`'${ws.selenium}'`, `'${webdriver}'`];
      break;
    case "e_win":
      args = [`"${ws.selenium}"`, `"${webdriver}"`];
      break;
    case "f":
      args = [
        `'${ws.selenium}'`,
        `'${webdriver}'`,
        `'${keywords.join(",")}'`,
        `'${comments.join(",")}'`,
        `'${like_limit}'`,
        `'${like_rate}'`,
        `'${collect_limit}'`,
        `'${collect_rate}'`,
        `'${comment_limit}'`,
        `'${comment_rate}'`,
        `'${duration}'`,
        `'${user.userInfo.token}'`,
        `'${id}'`,
      ];
      break;
    case "f_win":
      args = [
        `"${ws.selenium}"`,
        `"${webdriver}"`,
        `"${keywords.join(",")}"`,
        `"${comments.join(",")}"`,
        `"${like_limit}"`,
        `"${like_rate}"`,
        `"${collect_limit}"`,
        `"${collect_rate}"`,
        `"${comment_limit}"`,
        `"${comment_rate}"`,
        `"${duration}"`,
        `"${user.userInfo.token}"`,
        `"${id}"`,
      ];
      break;
  }

  const downloadUrl = pythons[key];

  self.postMessage({
    type: "downloadAndExecute",
    options: {
      downloadUrl,
      args,
      filename,
    },
  });

  // 等待主线程返回 downloadAndExecute 的响应数据
  const new_result = await new Promise((resolve) => {
    self.addEventListener("message", (event) => {
      if (event.data.type === "downloadAndExecuteResponse") {
        resolve(event.data.response);
      }
    });
  });

  const maintenances = ["f", "f_win"];
  if (new_result.code !== 0 && maintenances.indexOf(key) === -1) {
    await task_report({
      status: 0,
      is_finish: false,
      reason: result,
      task_id: task.id,
      xhs_user_id,
    });
  }

  if (new_result.code === 0 && maintenances.indexOf(key) === -1) {
    await task_report({
      status: 1,
      is_finish: true,
      note_id: new_result.data.noteId,
      task_id: task.id,
      xhs_user_id,
    });
  }

  if (maintenances.indexOf(key) !== -1) {
    await account_maintenance_task_report({
      id: task.id,
    });
  }

  self.postMessage({
    type: "fetch",
    url: `http://local.adspower.net:50325/api/v1/browser/stop?user_id=${encodeURIComponent(
      ads_power_id
    )}`,
    options: {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    },
  });
};

self.addEventListener("message", async (event) => {
  if (event.data.type !== "req") return;
  const { task, ads_powers, user, pythons, exact_key } = event.data; // 从主线程接收数据
  console.log("event.data", event.data);
  for (let j = 0; j < ads_powers.length; j++) {
    const { ads_power_id } = ads_powers[j];
    const keys = {
      0: "c",
      1: "d",
      2: "e",
      3: "f",
    };
    let key = keys[task.type_int];
    const pyjs = {
      0: `${key}${exact_key}_image_publish`,
      1: `${key}${exact_key}_video_publish`,
      2: `${key}${exact_key}_note_data`,
      3: `${key}${exact_key}_account_maintenance`,
    };
    let filename = pyjs[task.type_int];

    try {
      await openBrowser(
        ads_powers[j],
        1,
        task,
        `${key}${exact_key}`,
        filename,
        user,
        pythons
      );
    } catch (err) {
      // 脚本执行异常关闭浏览器
      self.postMessage({
        type: "fetch",
        url: `http://local.adspower.net:50325/api/v1/browser/stop?user_id=${encodeURIComponent(
          ads_power_id
        )}`,
        options: {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
          },
        },
      });
    }
  }
  console.log('worker doing')
  self.postMessage({ status: "done" });
});
